--[[
FilePath: \Lua\View\UIActivitySignIn\UIActivitySignIn.lua
特惠基金
--]]

require 'View/UIBase/UIBase'

UIActivitySignIn = UIBase.New(PanelNames.UIActivitySignIn)
local _M = UIActivitySignIn

_M.hasInit = false
_M.tabIndex = 1
_M.localRewardItems = nil
_M.getReward = false

function _M.Init(func, id)
    _M.activeId = id
    UIBase.Init(_M, func)
end

function _M:OnCreate()
    if not _M.hasInit then
        self:RegisterOnClick(self:GetChild("Backbtn"), self.OnBack)
        self.banner = self:GetChild("bannerBg")
        self.CoinLb = self:GetChild("CoinLb")
        self.bgSignTips2 = self:GetChild("BgSign2Tips")
        self.itemIcon = self:GetChild("ItemIcon")
        self.bannerText = self:GetChild("bannerText")
        self.signTips2 = self:GetChild("Sign2Tips")
        self.signNum2 = self:GetChild("Sign2Num")
        self.txtNum = self:GetChild("number");
        self.title = self:GetChild("title")
        self.signList = self:GetChild("SignList")
        self.btnSign1 = self:GetChild("btnSign1")
        self.signController1 = self.btnSign1:GetChild("UIRedDots"):GetController("c1")
        self.btnSign2 = self:GetChild("btnSign2")
        self.signController2 = self.btnSign2:GetChild("UIRedDots"):GetController("c1")
        self.buyBanner = self:GetChild("BuyBanner")
        self.btnBug = self:GetChild("buttomBug")
        self.buyController = self:GetController("buy")
        self.signInController = self:GetController("SignIn")
        self.isShowController = self:GetController("IsShow")

        self.signList.itemRenderer = self.refreshItem;

        if self.activeId ~= nil then
            self.activityTabConfig = G.dataTable["t_activitylist"][tostring(self.activeId)];
            self.activeConfigModel = G.dataTable[tostring(_M.activityTabConfig.f_ModelName)][tostring(self.activeId)];
        end
        self:addEvent()
        self:InitView()

        _M.hasInit = true
    end
end

function _M:addEvent()
    self.btnSign1.onClick:Add(self.onClickSign1, self);
    self.btnSign2.onClick:Add(self.onClickSign2, self);
    self.btnBug.onClick:Add(self.onClickBuy, self);
    self:RegisterEvent(Config.EventType.Fresh_Active,self.RefreshActive);
end

function _M:removeEvent()
    self.btnSign1.onClick:Remove(self.onClickSign1);
    self.btnSign2.onClick:Remove(self.onClickSign2);
    self.btnBug.onClick:Remove(self.onClickBuy);
end

function _M:InitView()
    if self.activeConfigModel ~= nil then
        if self.activeConfigModel.f_Banner ~= nil and self.activeConfigModel.f_Banner ~= "" then
            self.banner.url = self.activeConfigModel.f_Banner;
        end
        --self.title.text = getLanguage(self.activeConfigModel.f_Title);
        self.needMoneyName =HelperFunc.GetItemNameWithoutColor(getLanguage(dataTable.getRow("t_item",1)["f_ItemName"]))
        self.CoinLb.icon = EnumConst.AtlasPath.ItemAtlas .. G.dataTable["t_item"]["1"].f_Icon;
        self.btnBug.text = "￥"..self.activeConfigModel.f_Price;
        if self.activeConfigModel.f_FirstReward ~= nil and self.activeConfigModel.f_FirstReward ~= "" then
            local rewards = decodeJsonStrToTabel(self.activeConfigModel.f_FirstReward)
            self.signNum2.text = tostring(rewards[1][2]);
        else
            self.signNum2.text = "";
        end
        self.txtNum.text = self.activeConfigModel.f_number;
    end
    self.signTips2.text = getLanguage("ActivityDesc1100206")
    self.buyBanner.text = getLanguage("ActivityDesc1100207")
    self.btnSign1.text = getLanguage("ActivityDesc1100201")
    self.btnSign2.text = getLanguage("ActivityDesc1100202")
end

function _M:onClickSign1()
    if self.tabIndex == 0 then
        return;
    end
    self.tabIndex = 0;
    self:updateItem();
end

function _M:onClickSign2()
    if self.tabIndex == 1 then
        return;
    end
    self.tabIndex = 1;
    self:updateItem();
end

function _M:onClickBuy()
    if self.getReward then
        return;
    end

    if self.activeConfigModel == nil then
        return;
    end

    local severData, monthCardData, modelTableData = logicMgr.CostManager.getCostData(10101);
    if severData == nil or severData.items == nil then
        return;
    end

    local items = severData.items;
    local hasAct = false;
    for k, v in pairs(items) do
        if v.subId == 101011 or v.subId == 101012 then
            if tonumber(v.remainDay) > 0 then
                hasAct = true;
                --[[
                local cfg = G.dataTable["t_monthlycard"][tostring(v.subId)]
                if cfg ~= nil then
                    local pop = CtrlManager.GetCtrl(PanelNames.UICommonPop);
                    pop.Init("60", function(b)
                        if b then
                            closeUI(PanelNames.UIActivitySignIn);
                            closeUI(PanelNames.UIActivity);
                            showUI(PanelNames.UIHeadMenu);
                            logicMgr.CostManager.gotoCostById(10101);
                        end
                    end, getLanguage(cfg.f_MonthlyCardName));
                end
                return ;
                --]]
            end
        end
    end
    if not hasAct then
        local pop = CtrlManager.GetCtrl(PanelNames.UICommonPop);
        pop.Init("60", function(b)
            if b then
                closeUI(PanelNames.UIActivitySignIn);
                closeUI(PanelNames.UIActivity);
                showUI(PanelNames.UIHeadMenu);
                logicMgr.CostManager.gotoCostById(10101);
            end
        end);
        return;
    end

    --self.getReward = true;
    logicMgr.CostManager.BuyCostType(self.activeId, {self.activeConfigModel.f_ProductId}, self.activeConfigModel.f_ProductId, 1, 2, self.activeConfigModel.f_Price, nil, self);
end

-- 显示
function _M:OnEnable()
    self:Refresh(true);
end

function _M:RefreshActive()
    self:Refresh(false);
end

function _M:Refresh(isChange)
    if self.activeId == nil or not _M.hasInit then
        self:OnBack();
    else
        self.tableData, self.serverData, self.fundItemConfig = logicMgr.ActiveManager.getActiveData(self.activeId);
        if self.serverData == nil then
            self:OnBack();
            return;
        end
    end
    self.CostNum = tonumber(self.tableData.f_ResignCost)
    self.haveNum = logicMgr.ItemManager.getBagNumByTableID(1);
    self.CoinLb.title = self.haveNum;

    self.getReward = false;
    if self.serverData.buy168 then
        self.buyController.selectedIndex = 1;
    else
        self.buyController.selectedIndex = 0;
    end
    if isChange then
        --[[
        if self.serverData.rewardIndex == -1 then
            self.tabIndex = 1;
        else
            self.tabIndex = self.serverData.rewardIndex;
        end
        --]]
        if logicMgr.CostManager.getPlayerRechargeNum() > 0 then
            self.tabIndex = 1;
            self.isShowController.selectedIndex = 1;
        else
            self.tabIndex = 0;
            self.isShowController.selectedIndex = 0;
        end
        self.signInController.selectedIndex = self.tabIndex;
    end

    self:updateItem();
    self.signController1.selectedIndex = 0;
    if self.serverData.signRed then
        self.signController1.selectedIndex = 2;
    end
    self.signController2.selectedIndex = 0;
    if self.serverData.specialSignRed then
        self.signController2.selectedIndex = 2;
    end
    local time = HelperFunc.GetServerTime();
    self.endCountDown = self.serverData.endTime - time;
    self:updateActiveCountDown();
    self:TimeCall(self.updateActiveCountDown, 1000, -1);
end

function _M:updateActiveCountDown()
    if self.endCountDown == nil then
        return;
    end
    if self.endCountDown <= 0 then
        self.bannerText.text =  getLanguage("Sys_ActivityEnd");
        self:RemoveTimeCall(self.updateActiveCountDown)
    else
        self.bannerText.text = string.format(getLanguage("Sys_ActivityTimeLeft"), HelperFunc.GetSurpTimeStr(self.endCountDown));
    end
    self.endCountDown = self.endCountDown - 1;
end

function _M:updateItem()
    self.title.text = getLanguage("ActivityDesc1100201");
    self.localRewardItems = nil;
    if self.tabIndex == 0 and self.fundItemConfig ~= nil and self.fundItemConfig.commonItems ~= nil then
        self.localRewardItems = self.fundItemConfig.commonItems;
    elseif self.tabIndex == 1 and self.fundItemConfig ~= nil and self.fundItemConfig.payItems ~= nil then
        self.localRewardItems = self.fundItemConfig.payItems;
        self.title.text = getLanguage("ActivityDesc1100202");
    end
    if self.localRewardItems == nil then
        self.signList.numItems = 0;
    else
        self.signList.numItems = #self.localRewardItems;
    end
end

function _M.refreshItem(index, itemObj)
    local localIndex = index + 1;
    local rewardIcon = itemObj:GetChild("ItemIcon")
    local hero = itemObj:GetChild("Hero")
    local textNum = itemObj:GetChild("TextNum")
    local textDay = itemObj:GetChild("TextDay")
    local textGet = itemObj:GetChild("TextGet")
    local textPatch = itemObj:GetChild("TextPatch")
    local typeController = itemObj:GetController("type")
    local stateController = itemObj:GetController("state")
    local chooseController = itemObj:GetController("ischoose")
    local heroController = itemObj:GetController("isHero")
    local lockController = itemObj:GetController("isLock")
    local spineController = itemObj:GetController("spine")
    local btnGet = itemObj:GetChild("BtnGet")
    btnGet.onClick:Clear();

    local localCfg = _M.localRewardItems[localIndex]
    textDay.text = string.format(getLanguage( "ActivityDesc1100203"), localCfg.f_FundClass)
    textGet.text = getLanguage("ActivityDesc1100204")
    textPatch.text = getLanguage("ActivityDesc1100205")
    if _M.tabIndex == 1 then
        typeController.selectedIndex = 1
        if _M.serverData.buy168 then
            lockController.selectedIndex = 1
        else
            lockController.selectedIndex = 0
        end
    else
        typeController.selectedIndex = 0
        lockController.selectedIndex = 1
    end
    stateController.selectedIndex = localCfg.statue

    if localCfg.statue == 3 then
        btnGet.onClick:Add(function()
            if _M.getReward then
                return
            end
            _M.getReward =  true
            ActivityHandler.sendReqActivityDrawRewardMessage({_M.activeId, tonumber(localCfg.f_FundId)});
        end)
    elseif localCfg.statue == 1 then
        btnGet.onClick:Add(function()
            if _M.getReward then
                return
            end
            if _M.haveNum >= _M.CostNum then
                local pop = CtrlManager.GetCtrl(PanelNames.UICommonPop);
                pop.Init("61", function(b)
                    if b then
                        _M.getReward =  true
                        ActivityHandler.sendReqActivityDrawRewardMessage({_M.activeId, tonumber(localCfg.f_FundId)});
                    end
                end, _M.CostNum);
            else
                UISysTips.AddMsg(string.format(getLanguage("Character_Tips19"),_M.needMoneyName))
            end
        end)
    end

    local rewards = decodeJsonStrToTabel(localCfg.f_FundReward)
    textNum.text = tostring(rewards[1][2])
    if localCfg.f_IsHero == 1 then
        heroController.selectedIndex = 1
        logicMgr.CostManager.RefreshItem(hero, rewards[1], {isShowBigNum = true})
    else
        heroController.selectedIndex = 0
        local singleItemConfig = logicMgr.CostManager.getItemOrEquipDataByIdAndNum(rewards[1][1], rewards[1][2])
        UIComponentInterface:SetItemAllById(rewardIcon, nil, nil, singleItemConfig.itemModelId)
        local constData = ItemManager.getItemConstDatabyModelId(singleItemConfig.itemModelId)
        if constData and constData.itemType == EnumConst.ItemTypeEnum.Title then
            rewardIcon.url = EnumConst.AtlasPath.ICONAtlas .. constData.icon
        end

        rewardIcon.onClick:Clear()
        rewardIcon.onClick:Add(function()
            if singleItemConfig.itemType == EnumConst.ItemTypeEnum.HeroEntity then
                for k, v in pairs(G.dataTable["t_drop"]) do
                    if tonumber(singleItemConfig.itemModelId) == tonumber(v.f_DropPoolId) then
                        local heroId = decodeJsonStrToTabel(v.f_Hero)
                        if heroId ~= nil then
                            showUI(PanelNames.UIDrawAnimation, heroId[1][1], nil, false, function()
                                closeUI(PanelNames.UIDrawAnimation)
                            end, nil, true, true)
                        end
                        return
                    end
                end
            end
            if logicMgr.ItemManager.IsEquip(singleItemConfig["itemModelId"]) then
                local shopEquipAllInfo = logicMgr.ShopManager.equipBaseInfo(singleItemConfig)
                showUI(PanelNames.UIEquipInfo, nil, shopEquipAllInfo)
            else
                showUI(PanelNames.UIBagItemInfo, singleItemConfig)
            end
        end)
    end

    if localCfg.f_IsEffects == 1 then
        spineController.selectedIndex = 1
    else
        spineController.selectedIndex = 0
    end
end

-- 隐藏
function _M:OnDisable()

end

-- 卸载
function _M:OnDestroy()
    self:removeEvent();
    self.hasInit = false
    self.tabIndex = 1
    self.localRewardItems = nil
    self:RemoveTimeCall(self.updateActiveCountDown)
end

return _M;